package cn.edu.fzu.delivery.handler.impl;

import cn.edu.fzu.delivery.domain.entity.Courier;
import cn.edu.fzu.delivery.domain.entity.Logistics;
import cn.edu.fzu.delivery.domain.entity.Network;
import cn.edu.fzu.delivery.domain.entity.SysUser;
import cn.edu.fzu.delivery.domain.enums.UserStatusEnum;
import cn.edu.fzu.delivery.domain.enums.UserTypeEnum;
import cn.edu.fzu.delivery.handler.DeliveryError;
import cn.edu.fzu.delivery.handler.DeliveryHandler;
import cn.edu.fzu.delivery.handler.DeliverySession;
import cn.edu.fzu.delivery.service.CourierService;
import cn.edu.fzu.delivery.service.NetworkService;
import cn.edu.fzu.delivery.service.UserService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 快递员池构建
 *
 * @author fangxin
 * @date 2022/11/7
 */
@Component("courierPoolBuildHandler")
public class CourierPoolBuildHandler implements DeliveryHandler {

    @Resource
    private CourierService courierService;
    @Resource
    private UserService    userService;
    @Resource
    private NetworkService networkService;

    @Override
    public boolean process(DeliverySession session) {
        Courier courier = session.getCourier();

        Logistics logistics = courier.getLogistics();
        //如果没有分配网点，则根据寄件地址分配网点
        //已经分配网点，则从分配的网点中筛选快递员
        Network network = logistics == null ? courier.getSender().getNetwork() : logistics.getNetwork();
        session.setCurrentNetworkId(network.getId());
        session.setDestNetworkId(courier.getReceiver().getNetwork().getId());

        List<SysUser> deliveryMan = userService.listSysUser(network.getId(), null, UserTypeEnum.EXPRESS,
                UserStatusEnum.NORMAL, null, null, null);

        if (deliveryMan.isEmpty()) {
            session.setError(DeliveryError.NO_DELIVERYMAN);
            return false;
        }
        session.setDeliveryManPool(deliveryMan);
        return true;
    }
}
